module.exports = app => {

  const express = require('express')
  const assert = require('http-assert')
  const jwt = require('jsonwebtoken')
  const AdminUser = require('../../models/AdminUser')

  const router = express.Router()

  //创建资源接口
  router.post('/', async (req, res) => {
    const result = await req.model.create(req.body)
    res.send(result)
  })
  //获取全部资源接口
  router.get('/', async (req, res) => {
    let queryOptions = {}
    switch (req.model.modelName) {
      case 'Category':
        queryOptions.populate = 'categories'
    }
    const result = await req.model.find().setOptions(queryOptions)
    res.send(result)
  })
  // 获取某一资源接口
  router.get('/:id', async (req, res) => {
    const result = await req.model.findById(req.params.id)
    res.send(result)
  })
  // 修改资源接口
  router.put(`/:id`, async (req, res) => {
    const result = await req.model.findByIdAndUpdate(req.params.id, req.body, { new: true })
    res.send(result)
  })
  // 删除资源接口
  router.delete(`/:id`, async (req, res) => {
    const result = await req.model.findByIdAndRemove(req.params.id)
    res.send(result)
  })
  //登录校验中间件
  const admincheck = require('../../middleware/adminCheck')
  const classify = require('../../middleware/classify')
  app.use('/api/admin/rest/:resources', admincheck(), classify(), router)
  //处理图片操作
  const multer = require('multer')
  const path = require('path')
  upload = multer({ dest: path.join(__dirname, '../../uploads') })
  app.post('/api/admin/upload', admincheck(), upload.single('file'), (req, res) => {
    //读取图片信息
    file = req.file
    //设置图片URL，方便前端可以访问到
    file.url = `http://localhost:3000/uploads/${req.file.filename}`
    res.send(file)
  })
  //处理登录接口
  app.post('/api/admin/login', async (req, res) => {
    const assert = require('http-assert')
    const bcrypt = require('bcrypt')
    const { username, password } = req.body
    // 1.判断数据库中有没有该用户
    const user = await AdminUser.findOne({ username }).select('+password')
    assert(user, 422, '用户不存在')
    // 2.根据密码进行匹配
    const result = await bcrypt.compare(password, user.password)
    assert(result, '422', '密码错误，请重新输入')
    // 3.返回一个token
    const token = jwt.sign({ id: user._id }, req.app.get('psw'))
    res.send(token)

  })
  //错误处理中间件
  app.use((err, req, res, next) => {
    console.log(err);
    res.status(err.status || 500).send({ message: err.message })
  })
}